<template>
	<view class="content">
		<view class="head">
			<image src="../../static/star.jpg" mode="aspectFill"></image>
		</view>
		<!-- <image class="logo" src="/static/logo.png"></image> -->
		<mescroll-body ref="mescrollRef" :down="downOption" :up="upOption" @init="mescrollInit" @down="downCallback"
			@up="upCallback">
			<StarPostList :list="postList" :option="postOption" :my_user="children" @selectPost="selectPost"
				@longpressPost="longpressPost" @clickUserAvatar="clickPostUserAvatar"
				@clickUserNickname="clickPostUserNickname" @clickFocusUser="clickPostFocusUser"
				@clickChatUser="clickPostChatUser" @clickMore="clickMore" @clickSharePost="clickSharePost"
				@clickCommentPost="clickCommentPost" @toggleLike="togglePostLike">
			</StarPostList>
		</mescroll-body>
		<view class="release-fixed" @click.stop="clickReleasePost">
			＋
		</view>
	</view>
</template>
<script>
	import {
		BASE_URL
	} from '../../api';
	import StarPostList from '@/uni_modules/star-community/components/star-post-list/star-post-list.vue';
	import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js';
	import {
		mapState,
		mapActions
	} from 'vuex';
	export default {
		mixins: [MescrollMixin], // 使用mixin
		components: {
			StarPostList,
		},
		computed: {
			...mapState(['token', 'children', 'total_star', 'isLogin'])
		},
		data() {
			return {
				isFirstShow: true,
				title: 'Hello',
				text: '',
				toke: null,
				postList: [],
				posts: {},
				postOption: {
					lineShow: 6, // 文本超出多少行显示省略号
					// iconShare: '/static/share.svg',
					// iconView: '/static/view.svg',
					// iconComment: '/static/comment.svg',
					// iconLike: '/static/like.svg',
					// iconLiked: '/static/liked.svg',
				},
				downOption: {
					use: false, // 不启用mescroll下拉刷新，使用页面原生下拉刷新
				},
				upOption: {
					isBounce: false,
					noMoreSize: 4, // 如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看; 默认5
					toTop: {
						right: '20rpx',
						bottom: '160rpx',
						safearea: true,
						width: '100rpx',
						radius: '50%',
					}
				},
			}
		},
		onLaunch() {
			//this.checkStatus();
		},
		onShow() {
			this.checkStatus();
			if(this.isLogin == true){
				this.getPosts();
			}
			this.isFirstShow = false;
		},
		onPullDownRefresh() {
			this.mescroll.resetUpScroll()
			this.getPosts();
			uni.stopPullDownRefresh()
		},
		updated() {
			if(this.isFirstShow == false){
				this.checkStatus();
			}
			//console.log("同步token!");
			// console.log(this.toke);
			// this.askToken(this.toke);
		},
		methods: {
			// mescroll下拉刷新的回调
			downCallback() {
				// 这里加载你想下拉刷新的数据, 比如刷新轮播数据
				this.getPosts();
				// 下拉刷新的回调,默认重置上拉加载列表为第一页 (自动执行 page.num=1, 再触发upCallback方法 )
				this.mescroll.resetUpScroll()
			},
			async checkStatus() {
				if (this.isLogin == false) {
					await this.weixinLogin();
					//await this.login();
					//await this.getPosts();
				} else {
					uni.hideLoading();
				}
			},
			setToken(tk) {
				this.askToken(tk);
			},
			setChildren(cld) {
				this.updateChildren(cld);
			},
			getUserInfo() {
				return new Promise((resolve, reject) => {
					wx.showModal({
						title: '温馨提示',
						content: '亲，授权微信登录后才能正常使用小程序功能',
						success(res) {
							uni.showLoading({
							    title: '正在连接',
							    mask: true,
							});
							console.log(res);
							if (res.confirm) {
								uni.getUserProfile({
									lang: 'zh_CN',
									desc: '用户登录', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，
									success: (res) => {
										console.log(res, 'resss')
										resolve(res.userInfo)
									},
									fail: (err) => {
										reject(err);
									}
								})
							} else if (res.cancel) {
								//如果用户点击了取消按钮
								wx.showToast({
									title: '您拒绝了请求,不能正常使用小程序',
									icon: 'error',
									duration: 2000
								});
								return;
							}
						}
					})

				})
			},
			getLogin() {
				return new Promise((resolve, reject) => {
					uni.login({
						success(res) {
							console.log(res, 'res')
							resolve(res)
						},
						fail: (err) => {
							console.log(err, 'logoer')
							reject(err)
						}
					})
				})
			},
			weixinLogin() {
				//this.getUserInfo();
				//this.login();
				let that = this;
				let userInfo = that.getUserInfo();
				let loginRes = that.login();
				Promise.all([userInfo, loginRes]).then((result) => {
					console.log(result);
					let userInfo = result[0];
					let loginRes = result[1];
					this.toke = loginRes.data.data.token;
					this.setToken(loginRes.data.data.token);
					this.setChildren(loginRes.data.data.children);
					console.log(this.toke);
					this.text = 'request success';
					console.log(this.text);
					//this.isLogin = true;
					this.getPosts();
					this.updateLogin(true);
				})
				/*uni.getProvider({
					service: 'oauth',
					success: function(res) {
						//支持微信、qq和微博等
						if (~res.provider.indexOf('weixin')) {
							console.log(res, 'ress')
							let userInfo = that.getUserInfo();
							let loginRes = that.login();
							// let loginRes = that.getLogin();
							Promise.all([userInfo, loginRes]).then((result) => {
								console.log("result:");
								console.log(result);
								let userInfo = result[0];
								let loginRes = result[1];
								let access_token = loginRes.authResult.access_token;
								let openid = loginRes.authResult.openid;
								let data = Object.assign(loginRes.authResult, userInfo);
								that.$store.dispatch('Login', {
									type: 'weixin',
									url: that.url,
									data
								}).then(r => {
									if (r == 'ok') {
										uni.hideLoading()
									}
								}).catch(err => {
									uni.hideLoading();
									uni.showToast({
										icon: 'none',
										title: err
									})
								})
							})

						}
					},
					fail: function(err) {
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: err
						})
					}
				})*/
			},
			login() {
				return new Promise((resolve, reject) => {
					let openid = '';
					uni.login({
						provider: "weixin",
						success: (res) => {
							let appid = "wx080671d04cbe59cf";
							let secret = "07f71d3d1bdb1486b49934094a497068";
							let url =
								"https://api.weixin.qq.com/sns/jscode2session?appid=" +
								appid +
								"&secret=" +
								secret +
								"&js_code=" +
								res.code +
								"&grant_type=authorization_code";
							uni.request({
								url: url, // 请求路径
								success: (r) => {
									console.log("r", r);
									console.info("用户的openId", r.data.openid);
									uni.request({
										url: BASE_URL + '/children/login?openId=' + r.data
											.openid,
										method: 'POST',
										data: {},
										success: (res) => {
											console.log(res.data);
											// this.toke = res.data.data.token;
											// this.setToken(res.data.data.token);
											// this.setChildren(res.data.data.children);
											// console.log(this.toke);
											// this.text = 'request success';
											// console.log(this.text);
											// this.isLogin = true;
											// this.getPosts();
											resolve(res);
										},
										fail: (err) => {
											console.log(err, 'logoer')
											reject(err)
										}
									});
								},
								fail: (err) => {
									console.log(err, 'logoer')
									reject(err)
								}
							});
						},
						fail: (err) => {
							console.log(err, 'logoer')
							reject(err)
						}
					});
					
					if (this.toke != null) {
						console.log("非空！");
						console.log(this.toke)
					} else {
						console.log("空！");
					}
				})
			},
			getPosts() {
				uni.request({
					url: BASE_URL + '/post/getPosts',
					method: 'GET',
					header: {
						"Authorization": this.token,
					},
					data: {
						childrenId: this.children.childrenId,
					},
					success: (res) => {
						console.log(res.data);
						this.posts = res.data.data;
						let list = this.getPostList(null)
						this.postList = [] // 如果是第一页需手动制空列表
						this.postList = [...this.postList, ...list] // 追加新数据
						this.mescroll.endSuccess(list.length);
						this.text = 'request success';
						console.log(this.text);
					}
				});
			},
			async upCallback(page) {
				try {
					// 请求数据列表
					let list = await this.getPostList(page)
					// 设置列表数据
					/*if (page.num === 1) this.postList = [] // 如果是第一页需手动制空列表
					this.postList = [...this.postList, ...list] // 追加新数据*/
					this.postList = list;
					// 联网成功的回调,隐藏下拉刷新和上拉加载的状态
					//this.mescroll.endSuccess(this.postList.length);
					this.mescroll.endBySize(page.size, this.postList.length);
				} catch (err) {
					console.log(err)
				}
			},
			getPostList(page) {
				return this.generatePostList(this.posts.length);
				// return this.generatePostList(page.size);
			},
			generateOnePost(post) {
				return {
					id: post.post.postId,
					user_id: this.children.childrenId,
					avatar: post.avatar,
					nickname: post.childrenName,
					createTime: new Date(post.postRecord.releaseTime), // 生成一个时间戳范围内的随机时间戳,
					content: post.post.postContent,
					imgList: post.postPhoto,
					shareCount: 10,
					viewCount: 10,
					commentCount: post.postRecord.commentNumber,
					likeCount: post.postRecord.likesNumber,
				};
			},
			generatePostList(num) {
				let numPosts = num;
				if (numPosts > this.posts.length) {
					numPosts = this.posts.length;
				}
				const postList = [];
				for (let i = 0; i < numPosts; i++) {
					const newPost = this.generateOnePost(this.posts[i]);
					postList.push(newPost);
				}
				return postList;
			},
			// 选中贴子
			selectPost(post) {
				let pst = {};
				for (let i = 0; i < this.posts.length; i++) {
					if (this.posts[i].post.postId == post.id) {
						pst = this.posts[i];
						break;
					}
				}
				console.log('selectPost');
				this.goto('../post-detail/post-detail?post=' + JSON.stringify(post) + '&pst=' + JSON.stringify(pst));
			},
			// 长按帖子
			longpressPost(post) {
				console.log('longpressPost');
				this.showPostMoreActionSheet(post)
			},
			// 点击帖子中的关注用户
			clickPostFocusUser(post) {
				console.log('clickPostFocusUser');
				uni.showToast({
					title: '关注成功'
				})
			},
			// 点击帖子中的私聊用户
			clickPostChatUser(post) {
				console.log('clickPostChatUser')
				uni.showToast({
					title: '私聊界面开发中',
					icon: 'none'
				})
			},
			// 点击帖子更多
			clickMore(post) {
				console.log('clickMore');
				this.showPostMoreActionSheet(post)
			},
			// 点击分享帖子
			clickSharePost(post) {
				console.log('clickSharePost');
			},
			// 点击评论帖子
			clickCommentPost(post) {
				console.log('clickCommentPost');
				// 建议跳转后自动下滑到评论区
				this.goto(`../post-detail/post-detail?id=${post.post.postId}&comment=yes`)
			},
			// 点击帖子用户头像
			clickPostUserAvatar(post) {
				console.log('clickPostUserAvatar');
				//this.goto(`../homepage/homepage?id=${post.user_id}`)
			},
			// 点击贴子用户昵称
			clickPostUserNickname(post) {
				console.log('clickPostUserNickname');
				//this.goto(`../homepage/homepage?id=${post.user_id}`)
			},
			// 点赞帖子
			togglePostLike(post, isLiked) {
				console.log('togglePostLike', isLiked);
			},
			// 点击发布帖子按钮
			clickReleasePost() {
				this.goto('../post-release/post-release')
			},
			// 显示帖子更多操作菜单选项
			showPostMoreActionSheet(post) {
				uni.showActionSheet({
					itemList: ['举报'],
					success: (res) => {
						console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
						uni.showToast({
							title: '举报成功'
						})
					},
					fail: (res) => {
						console.log(res.errMsg);
					}
				});
			},
			goto(url) {
				uni.navigateTo({
					url
				})
			},
			...mapActions(['askToken', 'updateChildren', 'addStar', 'updateLogin'])
		}
	}
</script>

<style scoped lang="scss">
	.head {
		height: 400upx;
		background-color: aliceblue;
		display: flex;
		flex-flow: column;
		align-items: center;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200upx;
		width: 200upx;
		margin-top: 200upx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50upx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}

	.release-fixed {
		position: fixed;
		/* #ifdef MP */
		bottom: 50upx;
		/* #endif */
		/* #ifndef MP */
		bottom: calc(130upx + constant(safe-area-inset-bottom));
		bottom: calc(130upx + env(safe-area-inset-bottom));
		/* #endif */
		right: 20upx;
		background-color: #55aaff;
		color: #fff;
		height: 100upx;
		width: 100upx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		font-size: 65upx;
		font-weight: bold;
	}

	.cross {
		text-align: center;
		vertical-align: middle;
	}
</style>